import {
  SHOW_SUCCESS_MSG,
  SHOW_ERROR_MSG,
  SET_VOTES,
  SET_VOTE_DETAIL,
  CLEAN_VOTES,
  SET_VOTES_LOAD_ERR,
  SET_VOTES_NO_MORE
} from '../mutation-types'
import {
  createVote,
  getVoteListByPage,
  getVoteDetailById,
  deleteVoteById
} from '@/api/vote';

const state = {
  voteList: undefined, //全部投票列表
  voteListLoadErr: false, //投票列表加载出错
  voteListNoMore: false, //投票列表没有更多
  currentPageNum: 1, //offset = (currentPageNum-1)*currentPageSize
  currentPageSize: 10, //limit = currentPageSize
  currentVote: {
    id: '',
    topic: '',
    type: '',
    deadline: 0,
    creatorId: '',
    creatorUsername: '',
    creatorAccount: '',
    createdAt: 0,
    updatedAt: 0,
    options: [] //[{"id": 1,"content": "象棋"}]
  } //当前投票详情
}

const getters = {}

const actions = {
  //请求创建投票
  reqCreateVote({
    commit,
    state
  }, payload) {
    return new Promise((resolve, reject) => {
      createVote(payload).then(response => {
        let {
          data: result
        } = response;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            time: 2000,
            needGoBack: true,
            messagecode: `create-vote-${result.states}`
          });
        } else {
          commit(SHOW_ERROR_MSG, {
            messagecode: `err-service-unknow-500`
          });
        }
        resolve(response);
      }).catch(error => {
        reject(error)
      });
    });
  },
  //刷新获取投票列表（分页）
  reqRefreshGetVoteListByPage({
    dispatch,
    commit,
    state
  }, payload) {
    if (state.voteList) {
      commit(CLEAN_VOTES);
    }
    commit(SET_VOTES_NO_MORE, false);
    dispatch('reqGetVoteListByPage', payload);
  },
  //获取投票列表（分页）
  reqGetVoteListByPage({
    commit
  }, payload) {
    return new Promise((resolve, reject) => {
      getVoteListByPage(payload).then(response => {
        let {
          data: result
        } = response;
        if (result.states == 200) {
          commit(SET_VOTES, result.results);
          if (result.results.length == 0) {
            commit(SET_VOTES_NO_MORE, true);
            commit(SHOW_SUCCESS_MSG, {
              messagecode: `get-votelist-has-no-more`
            });
          }
          if (state.voteListLoadErr) {
            commit(SET_VOTES_LOAD_ERR, false);
          }
        } else {
          commit(SET_VOTES_LOAD_ERR, true);
        }
        resolve(response);
      }).catch(error => {
        commit(SET_VOTES_LOAD_ERR, true);
        reject(error)
      });
    });
  },
  //获取投票详情
  reqGetVoteDetailById({
    commit,
    state
  }, payload) {
    return new Promise((resolve, reject) => {
      getVoteDetailById(payload).then(response => {
        let {
          data: result
        } = response;
        if (result.states == 200) {
          commit(SET_VOTE_DETAIL, result.results);
        } else {

        }
        resolve(response);
      }).catch(error => {
        reject(error)
      });
    });
  },
  //删除投票
  reqDeleteVoteById({
    commit,
    state
  }, payload) {
    return new Promise((resolve, reject) => {
      deleteVoteById(payload).then(response => {
        let {
          data: result
        } = response;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            time: 2000,
            needGoBack: true,
            messagecode: `delete-vote-${result.states}`
          });
        } else {
          commit(SHOW_ERROR_MSG, {
            messagecode: `err-service-unknow-500`
          });
        }
        resolve(response);
      }).catch(error => {
        reject(error)
      });
    });
  },
}

const mutations = {
  [SET_VOTES](state, votes) {
    if (state.voteList) {
      state.voteList = [...state.voteList, ...votes];
    } else {
      state.voteList = votes;
    }
  },
  [SET_VOTE_DETAIL](state, vote) {
    state.currentVote = vote;
    state.currentVote.options = vote.options.map(item => {
      return {
        key: item.id,
        value: item.content
      };
    });
  },
  [CLEAN_VOTES](state) {
    state.voteList = [];
  },
  [SET_VOTES_LOAD_ERR](state, isErr) {
    state.voteListLoadErr = isErr;
  },
  [SET_VOTES_NO_MORE](state, isHasNoMore) {
    state.voteListNoMore = isHasNoMore;
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
